# -*- coding: utf-8 -*-
##############################################################
#  需要安装 numpy ,pandas包                                  #
#  pip3 install numpy                                        #
#  pip3 install pandas                                       #
#  pip3 install rarfile                                      #
#  功能:原始升级包的排序,重命名,需要手工删除原始压缩包       #
#  需要将原始升级包放入同一个目录下                          #
##############################################################
import pathlib, re, os, platform, rarfile, shutil
import pandas as pd
from hundsun_config import HARDWARE_BITMODE


def get_pack_sort(x):
    pattern = re.compile('V\d{6}[A-Za-z]?\-\d{2}[A-Za-z]?\-\d{3}[A-Za-z]?\d?',
                         re.I)
    if re.search(pattern, x['rar_name']):
        if re.search('增值程序', x['rar_name']):
            return str(
                re.sub('[a-zA-Z\-]', '',
                       re.search(pattern, x['rar_name']).group()) + '1').ljust(
                           15, '0')
        else:
            return str(
                re.sub('[a-zA-Z\-]', '',
                       re.search(pattern,
                                 x['rar_name']).group())).ljust(15, '0')
    else:
        return str(int('9' * 15))


if __name__ == "__main__":
    print("""
    目录结构要求：
    ├─UF20
    │  ├─32
    │  └─64
    ├─多金融
    │  ├─32位
    │  └─64位
    └─转融通
        ├─32
        └─64
    """)
    while True:
        #需要输入目录，如 d:\hundsun_files\*  hundsun_files目录下包含了所有的用于升级的文件。
        uf20path = input('请输入按照业务区分的升级包业务，将自动删除不需要位数的数据包,[q 退出]:')
        if uf20path == 'q':
            os._exit(0)
        elif pathlib.Path(uf20path).exists():
            break
        else:
            print('文件路径不合法,请重新输入')

    dirname = pathlib.Path(uf20path).resolve()
    if 'HARDWARE_BITMODE' in locals() or 'HARDWARE_BITMODE' in globals():
        #删除不需要的目录文件信息
        [
            shutil.rmtree(x) for x in dirname.iterdir() if x.is_dir()
            and not re.search(str(HARDWARE_BITMODE) + '[位]*', x.name)
        ]
        need_to_deal_list = [
            x for x in dirname.iterdir() if x.is_dir()
            and re.search(str(HARDWARE_BITMODE) + '[位]*', x.name)
        ]
        for need_to_deal_dir in need_to_deal_list:
            [shutil.move(x, dirname) for x in need_to_deal_dir.glob('*')]
            shutil.rmtree(need_to_deal_dir, ignore_errors=False)
    subname = [x for x in dirname.iterdir()]

    rar_name = [x.name for x in subname]

    df = pd.DataFrame({'source_name': subname, 'rar_name': rar_name})

    df['order_by'] = df.apply(get_pack_sort, axis=1)
    df = df.sort_values('order_by')
    df['cum_order'] = list(str(x + 1).zfill(2) for x in range(len(df)))
    df['new_file_name'] = list(
        map(lambda x, y: x.parent.joinpath(y + x.name), df['source_name'],
            df['cum_order']))
    [print(pathlib.Path(y).name) for y in df.new_file_name]

    while True:
        remane_flag = input('是否按照如上输出进行排序,[y  是 ; n  否;q 退出]:')
        if remane_flag.lower() == 'q' or remane_flag.lower() == 'n':
            os._exit(0)
        elif remane_flag.lower() == 'y':
            list(
                map(lambda x, y: x.rename(y), df['source_name'],
                    df['new_file_name']))
            print('重命名文件成功')
            break
        else:
            print('输入不合法,请重新输入,[y  是 ; n  否;q 退出]:')

    while True:
        remane_flag = input('是否删除原始文件并自动解压,[y  是 ; n  否;q 退出]:')
        if remane_flag.lower() == 'q' or remane_flag.lower() == 'n':
            os._exit(0)
        elif remane_flag.lower() == 'y':
            if re.search('\d+', platform.machine()).group() == '64':
                rarfile.UNRAR_TOOL = str(
                    pathlib.Path(__file__).resolve().parent.joinpath(
                        'rar_x64', 'UnRAR.exe'))
            else:
                rarfile.UNRAR_TOOL = pathlib.Path(
                    __file__).resolve().parent.joinpath(
                        'rar_x32', 'UnRAR.exe')
            rarfiles = [(x, x.stem, rarfile.RarFile(str(x)),
                         x.parent.joinpath(x.stem)) for x in dirname.iterdir()
                        if x.is_file() and rarfile.is_rarfile(str(x))]
            for item in rarfiles:
                pathlib_name, str_name, rar_file, dir_name = item
                if dir_name.exists() and dir_name.is_dir():
                    try:
                        shutil.rmtree(dir_name)
                        print('删除目录' + str(dir_name) + '成功:')

                    except:
                        print('删除目录' + str(dir_name) + '失败:')
                else:
                    try:
                        dir_name.mkdir()
                        print('创建目录' + str(dir_name) + '成功:')

                    except:
                        print('创建目录' + str(dir_name) + '失败:')
                    try:
                        print('#' * 20 + '开始解压' + '#' * 20)
                        print('文件:' + str(dir_name))
                        result = rar_file.extractall(path=str(dir_name))
                        print('#' * 20 + '结束解压' + '#' * 20)
                        if not result:
                            pathlib_name.unlink()
                            print('删除文件成功:' + str(pathlib_name))
                        else:
                            print('解压文件失败:' + str(pathlib_name))
                    except:
                        print('删除或解压文件' + str(pathlib_name) + '异常')
            print('解压删除压缩包文件成功')
            os._exit(0)
        else:
            print('是否删除原始文件并自动解压,[y  是 ; n  否;q 退出]:')